import goodsClassifyApi from '@/pages/Goods/ClassifyManagement/request';
import api from '@/pages/Goods/ListManagement/request';
import type { ProFormInstance } from '@ant-design/pro-components';
import { DrawerForm } from '@ant-design/pro-components';
import { Form, Tabs } from 'antd';
import { useMemo, useRef, useState } from 'react';
import { Coupon, Goods, Inventory } from './components';

export type FormConfig = { Component: any; props: Record<string, any> };
export interface Props {
  isEdit?: boolean;
  data?: Partial<GoodsListManagementApi.ListResponse>;
  visible?: boolean;
  onChangeVisible?: (visible: boolean) => void;
  onSuccess?: () => void;
  onCancel?: () => void;
}
const defaultFormData: GoodsListManagementApi.FormData = {
  goodsCategory: 0,
  goodsName: '',
  goodsClassifyId: '',
  goodsClassifyNames: '',
  sellPrice: 0,
  exhibitionPrice: 0,
  integral: 0,
  order: 0,
  isRecommend: false,
  isOnlyExchange: false,
  description: '',
  mainPicture: [],
  morePictureJson: [],
  bodyPictureJson: [],
  skuInput: [],
  couponTemplateInputs: {
    name: '',
    discountType: 2,
    discountValue: 0,
    minAmount: 0,
    expireDays: 0,
    qty: 0,
    description: '',
  },
};
function GoodsListManagementForm(props: Props) {
  const { data, isEdit = false, visible = false } = props;

  const formRef = useRef<ProFormInstance<any>>();
  const [form] = Form.useForm();
  const [activeKey, setActiveKey] = useState('goods');
  const [formData, setFormData] = useState<GoodsListManagementApi.FormData>({ ...defaultFormData });
  const [info, setInfo] = useState<Partial<GoodsListManagementApi.InfoResponse>>({});

  const [goodsClassifyList, setGoodsClasifyList] = useState<
    GoodsClassifyManagementApi.InfoResponse[]
  >([]);

  const getAllGoodsClassifyList = async () => {
    const data = await goodsClassifyApi.getAllList();
    setGoodsClasifyList(data);
  };
  const getInfo = async (params: GoodsListManagementApi.InfoParams) => {
    const info = await api.getInfo(params);
    const { mainPicture, morePictureJson, bodyPictureJson, ...data } = info;
    const formData: GoodsListManagementApi.FormData = {
      ...data,
      integral: 0,
      order: 0,
      mainPicture: [],
      morePictureJson: [],
      bodyPictureJson: [],
      skuInput: data.skuInput.map((item) => ({ ...item, id: data.goodsId })),
    };

    if (mainPicture) {
      formData.mainPicture = [
        {
          uid: mainPicture,
          name: mainPicture,
          url: mainPicture,
        },
      ];
    }
    if (morePictureJson) {
      formData.morePictureJson = JSON.parse(morePictureJson);
    }
    if (bodyPictureJson) {
      formData.bodyPictureJson = JSON.parse(bodyPictureJson);
    }
    setInfo(info);
    form.setFieldsValue(formData);
    setFormData(formData);
  };

  const onOpenChange = (open: boolean) => {
    if (open) {
      getAllGoodsClassifyList();
      if (data && data.goodsId) {
        getInfo({ id: data.goodsId });
      }
    } else {
      setInfo({});
      form.setFieldsValue({ ...defaultFormData });
      setFormData({ ...defaultFormData });
      props.onCancel?.();
    }
    props.onChangeVisible?.(open);
  };
  const onSubmit = async () => {
    const { mainPicture, morePictureJson, bodyPictureJson, ...restFormData } = formData;
    const { goodsId = '' } = info;

    if (isEdit) {
      const params: GoodsListManagementApi.UpdateParams = {
        ...restFormData,
        id: goodsId,
        mainPicture: mainPicture[0].url,
        morePictureJson: JSON.stringify(morePictureJson),
        bodyPictureJson: JSON.stringify(bodyPictureJson),
      };
      // 优惠券
      if (formData.goodsCategory === 0) {
        // 折扣类型值： 2: 全额抵扣（写死）
        params.couponTemplateInputs = { ...formData.couponTemplateInputs, discountType: 2 };
      } else {
        params.skuInput = formData.skuInput.map((item) => ({ ...item, id: goodsId }));
        params.couponTemplateInputs = { ...defaultFormData.couponTemplateInputs };
      }
      const data = await api.update(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    } else {
      const params: GoodsListManagementApi.CreateParams = {
        ...restFormData,
        mainPicture: mainPicture[0].url,
        morePictureJson: JSON.stringify(morePictureJson),
        bodyPictureJson: JSON.stringify(bodyPictureJson),
      };
      // 优惠券
      if (formData.goodsCategory === 0) {
        // 折扣类型值： 2: 全额抵扣（写死）
        params.couponTemplateInputs = { ...formData.couponTemplateInputs, discountType: 2 };
      } else {
        params.skuInput = formData.skuInput.map((item) => ({ ...item }));
      }
      const data = await api.create(params);
      if (data.success) props.onSuccess?.();
      return data.success;
    }
  };

  const tabsItems = useMemo(() => {
    const tabsItems = [
      {
        key: 'goods',
        label: '商品信息',
        children: (
          <Goods
            isEdit={isEdit}
            formData={formData}
            goodsClassifyList={goodsClassifyList}
            setFormData={setFormData}
          />
        ),
      },
    ];
    if (formData.goodsCategory === 0) {
      tabsItems.push({
        key: 'coupon',
        label: '优惠信息',
        children: <Coupon formRef={formRef} formData={formData} setFormData={setFormData} />,
      });
    } else {
      tabsItems.push({
        key: 'inventory',
        label: '库存信息',
        children: <Inventory formRef={formRef} formData={formData} setFormData={setFormData} />,
      });
    }
    return tabsItems;
  }, [isEdit, formRef, formData, goodsClassifyList, setFormData]);

  return (
    <DrawerForm
      autoFocusFirstInput
      title={`${isEdit ? '编辑' : '新建'}商品`}
      drawerProps={{
        destroyOnClose: true,
        bodyStyle: { padding: '0 15px' },
      }}
      formRef={formRef}
      form={form}
      resize={{
        maxWidth: window.innerWidth * 0.8,
        minWidth: 1080,
        onResize() {},
      }}
      open={visible}
      onOpenChange={onOpenChange}
      onFinish={onSubmit}
    >
      <Tabs
        accessKey={activeKey}
        items={tabsItems}
        onChange={(activeKey) => setActiveKey(activeKey)}
      ></Tabs>
    </DrawerForm>
  );
}

export default GoodsListManagementForm;
